package com.zone.vehicle.superapp.model;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.alibaba.fastjson.JSON;
import com.zone.lib.download.db.DownloadDaoUtilsStore;
import com.zone.lib.download.db.entity.Download;
import com.zone.lib.download.enums.AppStatusEnum;
import com.zone.lib.download.enums.AppTypeEnum;
import com.zone.lib.download.utils.AppStatusUpdateNotify;
import com.zone.lib.download.utils.SharedPreferencesUtil;
import com.zone.sdk.common.http.base.Result;
import com.zone.sdk.common.http.callback.ResultCallBack;
import com.zone.sdk.module.appstore.entity.AppDetailEntity;
import com.zone.vehicle.sdk.module.superapp.entity.AppUpdateEntity;
import com.zone.vehicle.sdk.module.superapp.response.AppPushResponse;
import com.zone.vehicle.superapp.bean.AppBean;
import com.zone.vehicle.superapp.repository.AppManagerRepository;
import com.zone.vehicle.superapp.utils.JDUtil;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

import lombok.Data;
import lombok.EqualsAndHashCode;

import static com.zone.lib.download.enums.AppStatusEnum.LIGHT_INSTALL_COMPLETE;
import static com.zone.sdk_api.common.Content.USER_ID;
import static com.zone.sdk_api.common.Content.VIN;

@Data
@EqualsAndHashCode(callSuper = false)
public class AppManagerViewModel extends ViewModel {

    private static final String TAG = AppManagerViewModel.class.getSimpleName();

    private final MutableLiveData<Result> error = new MutableLiveData<>();

    private MutableLiveData<List<AppBean>> activityApp = new MutableLiveData<>();

    private MutableLiveData<List<AppBean>> installedApp = new MutableLiveData<>();
    private MutableLiveData<List<AppBean>> installedLightApp = new MutableLiveData<>();
    private MutableLiveData<List<AppBean>> needUpdateApps = new MutableLiveData<>();
    private MutableLiveData<List<AppBean>> needUpdateApk = new MutableLiveData<>();
    private MutableLiveData<List<AppBean>> needUpdateLightApp = new MutableLiveData<>();

    private MutableLiveData<List<AppBean>> activityLightApp = new MutableLiveData<>();

    private AppManagerRepository repository;

    public AppManagerViewModel(AppManagerRepository repository) {
        this.repository = repository;
    }

    public MutableLiveData<List<AppBean>> getActivityApp() {
        return activityApp;
    }

    public MutableLiveData<List<AppBean>> getInstalledApp() {
        return installedApp;
    }

    public MutableLiveData<List<AppBean>> getActivityLightApp() {
        return activityLightApp;
    }

    public MutableLiveData<List<AppBean>> getInstalledLightApp() {
        return installedLightApp;
    }

    public MutableLiveData<List<AppBean>> getNeedUpdateApps() {
        return needUpdateApps;
    }

    public MutableLiveData<List<AppBean>> getNeedUpdateLightApp() {
        return needUpdateLightApp;
    }

    public MutableLiveData<Result> getError() {
        return error;
    }

    /**
     * 获取操作中APP：下载
     *
     * @param appTypeEnum
     */
    public void getActivityApp(Context context, AppTypeEnum appTypeEnum) {
        List<AppBean> appBeanList = repository.getActivityApps(appTypeEnum);
        if (ObjectUtils.isEmpty(appBeanList)) {
            if (appTypeEnum == AppTypeEnum.APP) {
                activityApp.setValue(new ArrayList<>());
            } else if (appTypeEnum == AppTypeEnum.APP_LIGHT) {
                activityLightApp.setValue(new ArrayList<>());
            }
            return;
        }
        for (int i = 0; i < appBeanList.size(); i++) {
            AppBean appBean = appBeanList.get(i);
            repository.getAppDetail(context, appBean.getCode(), new ResultCallBack<Result<AppDetailEntity>>() {
                @Override
                public void onSuccess(Result<AppDetailEntity> result) {
                    if (result.getResultCode().equals("200")) {
                        appBean.build(result.getData());
                        if (appTypeEnum == AppTypeEnum.APP) {
                            activityApp.setValue(appBeanList);
                        } else if (appTypeEnum == AppTypeEnum.APP_LIGHT) {
                            activityLightApp.setValue(appBeanList);
                        }
                    } else {
                        buildError(result.getResultCode(), result.getResultMsg());
                    }
                }

                @Override
                public void onError(String errorCode, String message) {
                }

                @Override
                public void onComplete() {
                }
            });
        }
    }

    /**
     * 获取操作中APP：下载
     *
     * @param
     */
    public void getDownloadApps(Context context, AppTypeEnum appTypeEnum) {
        List<AppBean> appBeanList = repository.getDownloadApps(appTypeEnum);
        Log.d(TAG, "getDownloadApps download=" + appBeanList.size());
        if (appTypeEnum == AppTypeEnum.APP) {
            activityApp.setValue(appBeanList);
        } else if (appTypeEnum == AppTypeEnum.APP_LIGHT) {
            activityLightApp.setValue(appBeanList);
        }
        for (int i = 0; i < appBeanList.size(); i++) {
            AppBean appBean = appBeanList.get(i);
            repository.getAppDetail(context, appBean.getCode(), new ResultCallBack<Result<AppDetailEntity>>() {
                @Override
                public void onSuccess(Result<AppDetailEntity> result) {
                    if (result.getResultCode().equals("200")) {
                        appBean.build(result.getData());
//                        if (appTypeEnum == AppTypeEnum.APP){
//                            activityApp.setValue(appBeanList);
//                        }else if (appTypeEnum == AppTypeEnum.APP_LIGHT){
//                            activityLightApp.setValue(appBeanList);
//                        }
                    } else {
                        buildError(result.getResultCode(), result.getResultMsg());
                    }
                }

                @Override
                public void onError(String errorCode, String message) {

                }

                @Override
                public void onComplete() {

                }
            });
        }
    }

    /**
     * 获取操作中APP：已安装
     *
     * @param
     */
    public void getInstallApps(Context context, AppTypeEnum appTypeEnum) {
        List<AppBean> appBeanList = repository.getInstallApps(appTypeEnum);
        if (appTypeEnum == AppTypeEnum.APP) {
            installedApp.setValue(appBeanList);
        } else if (appTypeEnum == AppTypeEnum.APP_LIGHT) {
            installedLightApp.setValue(appBeanList);
        }
        if (appTypeEnum == AppTypeEnum.APP) {
            repository.updateList(context, "", AppTypeEnum.APP, new ResultCallBack<Result<List<AppUpdateEntity>>>() {
                @Override
                public void onSuccess(Result<List<AppUpdateEntity>> result) {
                    if (result.getResultCode().equals("200")) {
                        if (ObjectUtils.isNotEmpty(result.getData())) {
                            for (int j = 0; j < result.getData().size(); j++) {
                                AppUpdateEntity entity = result.getData().get(j);
                                for (int i = 0; i < appBeanList.size(); i++) {
                                    AppBean appBean = appBeanList.get(i);
                                    if (entity.getCode().equals(appBean.getCode())) {
                                        appBean.setUpdateEntity(entity);
                                    }
                                }
                            }
                            installedApp.setValue(appBeanList);
                        }
                    }
                }

                @Override
                public void onError(String errorCode, String message) {

                }

                @Override
                public void onComplete() {

                }
            });

        }
    }


    public void downLoadApp(Context context, AppStatusEnum status, AppDetailEntity appEntity) {
        if (appEntity != null && StringUtils.isNotEmpty(appEntity.getAppType()) && appEntity.getAppType().equals(AppTypeEnum.APP_LIGHT.getName())) {
            appletPush(context, appEntity, status);
        } else if (appEntity != null && StringUtils.isNotEmpty(appEntity.getAppType()) && appEntity.getAppType().equals(AppTypeEnum.APP.getName())) {
            repository.downLoadApp(context, status.CODE, appEntity);
        } else {
            repository.downLoadApp(context, status.CODE, appEntity);
        }
    }

    public void updateApp(Context context, AppStatusEnum status, AppBean appBean) {
        if (appBean != null && StringUtils.isNotEmpty(appBean.getAppType()) && appBean.getAppType().equals(AppTypeEnum.APP_LIGHT.getName())) {
            appletPush(context, appBean, status);
        } else if (appBean != null && StringUtils.isNotEmpty(appBean.getAppType()) && appBean.getAppType().equals(AppTypeEnum.APP.getName())) {
            repository.updateApp(context, status.CODE, appBean);
        }
    }

    public void updateApk(Context context, AppStatusEnum status, AppDetailEntity appEntity) {
        if (ObjectUtils.isNotEmpty(appEntity)) {
            AppBean appBean = new AppBean();
            Download download = DownloadDaoUtilsStore.getInstance().getDownloadByCode(appEntity.getCode());
            if (ObjectUtils.isEmpty(download)) {
                return;
            }
            appBean.setDownload(download);
            repository.getAppDetail(context, appEntity.getCode(), new ResultCallBack<Result<AppDetailEntity>>() {
                @Override
                public void onSuccess(Result<AppDetailEntity> result) {
                    Log.d(TAG, "getAppDetail onSuccess=" + JSON.toJSONString(result));
                    if (result.getResultCode().equals("200")) {
                        AppDetailEntity appEntity1 = result.getData();
                        appBean.build(appEntity1);
                        repository.updateList(context, appEntity1.getCode(), AppTypeEnum.APP, new ResultCallBack<Result<List<AppUpdateEntity>>>() {
                            @Override
                            public void onSuccess(Result<List<AppUpdateEntity>> listResult) {
                                Log.d(TAG, "updateList onSuccess=" + JSON.toJSONString(listResult));
                                if (result.getResultCode().equals("200")) {
                                    if (ObjectUtils.isNotEmpty(listResult.getData())) {
                                        AppUpdateEntity appUpdateEntity = listResult.getData().get(0);
                                        appBean.setUpdateEntity(appUpdateEntity);
                                        repository.updateApp(context, status.CODE, appBean);
                                    }
                                }

                            }

                            @Override
                            public void onError(String errorCode, String message) {

                            }

                            @Override
                            public void onComplete() {

                            }
                        });

                    }

                }

                @Override
                public void onError(String errorCode, String message) {

                }

                @Override
                public void onComplete() {

                }
            });

        }
    }

    public void install(Context context, AppStatusEnum appStatusEnum, AppDetailEntity appEntity) {
        if (ObjectUtils.isNotEmpty(appEntity)) {
            if (appEntity.getAppType().equals(AppTypeEnum.APP.getName())) {
                repository.install(context, appEntity, appStatusEnum);
            } else if (appEntity.getAppType().equals(AppTypeEnum.APP_LIGHT.getName())) {
                appletPush(context, appEntity, appStatusEnum);
            }
        }
    }

    /**
     * 待更新应用
     *
     * @param context
     */
    public void getNeedUpdateApps(Context context) {
//        List<AppBean> installApps = repository.getInstalledApp(AppTypeEnum.APP);
        List<AppBean> installApps = repository.getLocalInstalledApps(AppTypeEnum.APP);
        if (ObjectUtils.isEmpty(installApps)) {
            needUpdateApps.setValue(new ArrayList<>());
            return;
        }
        List<AppBean> appBeanList = new ArrayList<>();
        repository.updateList(context, "", AppTypeEnum.APP, new ResultCallBack<Result<List<AppUpdateEntity>>>() {
            @Override
            public void onSuccess(Result<List<AppUpdateEntity>> result) {
                if (result.getResultCode().equals("200")) {
                    List<AppUpdateEntity> updateEntityList = result.getData();
                    if (ObjectUtils.isNotEmpty(updateEntityList)) {
                        for (int i = 0; i < updateEntityList.size(); i++) {
                            AppUpdateEntity updateEntity = updateEntityList.get(i);
                            for (int j = 0; j < installApps.size(); j++) {
                                AppBean appBean = installApps.get(j);
                                if (appBean.getCode().equals(updateEntity.getCode())) {
                                    appBean.setUpdateEntity(updateEntity);
                                    appBeanList.add(appBean);
                                    repository.getAppDetail(context, appBean.getCode(), new ResultCallBack<Result<AppDetailEntity>>() {
                                        @Override
                                        public void onSuccess(Result<AppDetailEntity> result1) {
                                            if (result.getResultCode().equals("200")) {
                                                AppDetailEntity entity = result1.getData();
                                                for (AppBean ben : appBeanList) {
                                                    if (ben.getCode().equals(entity.getCode())) {
                                                        ben.build(entity);
                                                        needUpdateApps.setValue(appBeanList);
                                                        break;
                                                    }
                                                }
                                            }
                                        }

                                        @Override
                                        public void onError(String errorCode, String message) {
                                        }

                                        @Override
                                        public void onComplete() {
                                        }
                                    });
                                }
                            }
                        }
                    } else {
                        needUpdateApps.setValue(new ArrayList<>());
                    }
                }
            }

            @Override
            public void onError(String errorCode, String message) {
            }

            @Override
            public void onComplete() {
            }
        });
    }

    public void startApp(Context context, AppBean appBean) {
        if (appBean.getAppType().equals(AppTypeEnum.APP_LIGHT.getName())) {
            JDUtil.start(context, appBean.getCode(), appBean.getAppType());
        } else if (appBean.getAppType().equals(AppTypeEnum.APP.getName())) {
            Intent intent = context.getPackageManager().getLaunchIntentForPackage(appBean.getPackageName());
            if (intent != null) {
                intent.setPackage(null);
                context.startActivity(intent);
            }
        }
    }

    /**
     * 卸载
     *
     * @param appBean
     */
    public void delete(Context context, AppBean appBean) {
        if (ObjectUtils.isNotEmpty(appBean)) {
            if (appBean.getAppType().equals(AppTypeEnum.APP_LIGHT.getName())) {
//                JDUtil.delete(context, appBean.getCode(), appBean.getAppType());
                appletPush(context, appBean, AppStatusEnum.LIGHT_DELETE);
                AppStatusUpdateNotify.sendAppState(appBean.getAppType(),
                        SharedPreferencesUtil.getInstance(context).getSP(VIN),
                        SharedPreferencesUtil.getInstance(context).getSP(USER_ID),
                        appBean.getCode(), AppStatusEnum.LIGHT_DELETE_SUCCESS.CODE,
                        "",
                        appBean.getVersion());
            } else if (appBean.getAppType().equals(AppTypeEnum.APP.getName())) {
                repository.delete(context, appBean);
                Download download = appBean.getDownload();
                if (ObjectUtils.isNotEmpty(download)) {
                    if (download.getDownloadStatus() == AppStatusEnum.INSTALL_SUCCESS.CODE) {
                        getInstallApps(context, AppTypeEnum.APP);
                    } else {
                        getDownloadApps(context, AppTypeEnum.APP);
                    }
                }

            }
        }
    }

    public void appletPush(Context context, AppDetailEntity appEntity, AppStatusEnum statusEnum) {
        repository.appletPush(context, appEntity, statusEnum, new ResultCallBack<Result<AppPushResponse>>() {
            @Override
            public void onSuccess(Result<AppPushResponse> result) {
                Download download = DownloadDaoUtilsStore.getInstance().getDownloadByCode(appEntity.getCode());
                if (ObjectUtils.isNotEmpty(download)) {
                    if (result.getResultCode().equals("200")) {
                        if (statusEnum == AppStatusEnum.LIGHT_DELETE
                                || statusEnum == AppStatusEnum.UNINSTALL_APP_AND_LIGHT) {
                            download.setDownloadStatus(AppStatusEnum.LIGHT_DELETE_SUCCESS.CODE);
                            DownloadDaoUtilsStore.getInstance().getDownloadAppDaoUtils().delete(download);
                        } else {
                            download.setDownloadStatus(LIGHT_INSTALL_COMPLETE.CODE);
                        }
                    } else {
                        if (statusEnum == AppStatusEnum.LIGHT_DELETE
                                || statusEnum == AppStatusEnum.UNINSTALL_APP_AND_LIGHT) {
                            download.setDownloadStatus(AppStatusEnum.LIGHT_DELETE_FAILED.CODE);
                        } else {
                            download.setDownloadStatus(AppStatusEnum.LIGHT_INSTALL_FAIL.CODE);
                        }
                        buildError(result.getResultCode(), result.getResultMsg());
                    }
                    AppStatusUpdateNotify.appNotify(context, download);
                }
                getActivityApp(context, AppTypeEnum.APP_LIGHT);
            }

            @Override
            public void onError(String errorCode, String message) {
                Download download = DownloadDaoUtilsStore.getInstance().getDownloadByCode(appEntity.getCode());
                if (statusEnum == AppStatusEnum.LIGHT_DELETE
                        || statusEnum == AppStatusEnum.UNINSTALL_APP_AND_LIGHT) {
                    download.setDownloadStatus(AppStatusEnum.LIGHT_DELETE_FAILED.CODE);
                } else {
                    download.setDownloadStatus(AppStatusEnum.LIGHT_INSTALL_FAIL.CODE);
                }
                AppStatusUpdateNotify.appNotify(context, download);
                buildError(errorCode, message);
            }

            @Override
            public void onComplete() {

            }
        });
    }

    public void updateList(Context context, String appCode, AppTypeEnum appTypeEnum) {
        repository.updateList(context, appCode, appTypeEnum, new ResultCallBack<Result<List<AppUpdateEntity>>>() {
            @Override
            public void onSuccess(Result<List<AppUpdateEntity>> appUpdateEntityResult) {

            }

            @Override
            public void onError(String errorCode, String message) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void buildError(String errorCode, String message) {
        Result result = new Result();
        result.setResultCode(errorCode);
        result.setResultMsg(message);
        error.setValue(result);
    }

}